package com.edu.interceptor;


import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

import com.edu.vo.ResultVO;

/**
 * 统一异常处理器
 *
 * @author Administrator
 */
public class ExceptionActionHandler {

    private static final String ERROR_VIEW = "error";
    @Autowired
    private MappingJackson2HttpMessageConverter jsonConverter;

    @ExceptionHandler(value = Exception.class)
    public Object error(HttpServletRequest request, HttpServletResponse response, Exception e) throws HttpMessageNotWritableException, IOException {
        if (isAjax(request)) {
            ResultVO result = ResultVO.getErrorResultVO(e.getMessage());
            jsonConverter.write(result, MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response));
            return null;
        } else {
            ModelAndView mav = new ModelAndView();
            mav.addObject("exception", e);
            mav.addObject("url", request.getRequestURL());
            mav.setViewName(ERROR_VIEW);
            return mav;
        }
    }

    /**
     * 判断是否是ajax请求
     *
     * @param request
     * @return
     */
    public static boolean isAjax(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        return (header != null && "XMLHttpRequest".equals(header));
    }

}
